<?php
// +----------------------------------------------------------------------
// | Jqcms [ Avenue to Jane ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017 http://jqcms.net All rights reserved.
// +----------------------------------------------------------------------
// | Author: hyacinth <845077398@qq.com>
// +----------------------------------------------------------------------
namespace Admin\Controller;
use Common\Controller\BaseController;

class CategoryController extends BaseController {
    
    public function index(){
       
        $category = M('Category');
        $where = "";
        $count = $category->where($where)->count();
        $p = getpage($count,10);
        $list = $category->field(true)->where($where)->order('id')->limit($p->firstRow, $p->listRows)->select();
        $this->assign('list', $list);
        $this->assign('page', $p->show());
        $this->display();
        
    }

    public function create(){
        
        $category = D('Category');
        if(IS_POST){
            // 批量添加数据
            if(I('post.title_list')!==""){
                
                $title_list = trim(I('title_list'));
                $title_arr = explode("\r\n", $title_list);
                foreach ($title_arr as $vv){
                    $dataList[]=array('title'=>$vv,'parent_id'=>$_POST['parent']);
                }
                $category->addAll($dataList);
                $this->success('批量添加成功!','index');
                
            }else{//普通添加
                
                if($category->create()){
                    $category->add();
                    $this->success('添加成功!','index'); 
                }else{
                    $this->error($category->getError());  
                }
            }
  
        }else{
            $data = $category->getCate();
            $this->assign('data',$data);
            $this->display();
        }
           
    }
    
    public function edit($id){
        
        $category = D('Category');
        if (IS_POST) {
            
            if($category->create()){
                $category->save();
                $this->success('编辑成功!','index');
            }else{
                $this->error($category->getError());
            }
             
        }else {
            $data = $category->find($id);
            $data['cate'] = $category->getCate();
            $this->assign('data',$data);
            $this->display();
        }
        
    }
    
    public function del($id){
    
        $cate = M('Category');
        $cid = $cate->where(array('parent_id'=>$id))->select();
        if ($cid==null){
            
            $del = $cate->delete($id);
            if($del !==0 && $del !==false){
                $this->success('删除成功!');
            }else {
                $this->error('删除失败!');
            }
      
        }else {
            
            $this->error('该分类下存在分类!');
        }
         
    }
    
  
    
}